package com.yuanda.erp9.syn.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * SpringContext工具类
 * 
 * @ClassName: SpringContextUtil
 * @Author: xuhao
 * @Date: 2021/3/29 15:47
 **/
@Component
public class SpringContextUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }

    /**
     * 获取ApplicationContext
     *
     * @return org.springframework.context.ApplicationContext
     * @author xuhao
     * @create 2021/3/29 16:48
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 根据beanName获取spring容器中对象
     *
     * @param beanName
     * @return T
     * @author xuhao
     * @create 2021/3/29 16:49
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String beanName) throws BeansException {
        return (T) applicationContext.getBean(beanName);
    }

    /**
     * 根据beanName获取spring容器中对象
     *
     * @param beanName
     * @return T
     * @author xuhao
     * @create 2021/3/29 16:49
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String beanName,Class clazz) throws BeansException {
        return (T) applicationContext.getBean(beanName,clazz);
    }


    /**
     * @Description: 返回T对象
     * @Params:  @T 接口、类 @bean bean名称 @clazz bean的实现类
     * @Return:
     * @Author: Mr.myq
     * @Date: 2022/12/2314:42
     */
    public static  <T> T getBean(Class<T> T,String bean,Class clazz){
        // 仅执行一次
        return (T)SpringContextUtil.getBean(bean,clazz);
    }



}

